<template>
  <div>
    <el-dialog
      :title="title"
      width="1200px"
      :before-close="handleClose"
      :visible="showNext"
    >
      <el-card v-for="item in groups" :key="item.NodeId" :header="item.NodeName">
        <el-form
          :ref="'form_'+item.NodeId"
          :model="item"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item v-if="item.Ignores && item.Ignores.length > 0" label="跳过的节点">
            <span v-for="(i,index) in item.Ignores" :key="i.NodeId" class="jumpNode">{{ (index + 1) + ',' + i.NodeName }}</span>
          </el-form-item>
          <el-form-item v-if="item.Node.length > 1 && item.OutPolicy !== 1" label="选择步骤" prop="ChioseNodeId">
            <el-checkbox-group v-model="item.ChioseNodeId" :min="item.min" :max="item.max">
              <el-checkbox-button v-for="k in item.Node" :key="k.ToNodeId" :label="k.ToNodeId">{{ k.NodeName }}</el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
          <el-timeline>
            <el-timeline-item v-for="(k,index) in filterNode(item)" :key="k.ToNodeId" color="#409eff" :hide-timestamp="true">
              <el-form-item label="下一节点">
                {{ k.NodeName }}
              </el-form-item>
              <template v-if="k.NodeType != 3">
                <el-form-item label="审批方式">
                  {{ FlowAuditType[k.AuditType].text }}
                </el-form-item>
                <el-form-item
                  v-if="k.NodeType != 3"
                  label="审核人"
                  :prop="'Node['+index+'].EmpId'"
                  :rules="{
                    required: true, message: '审核人不能为空', trigger: 'blur'
                  }"
                >
                  <div style="margin-bottom: 5px;">
                    <el-button v-if="k.FilterType !== 1" type="primary" size="mini" icon="el-icon-user" @click="chioseEmp(k)" />
                    <span style="margin-left: 20px;">{{ k.FilterShow }}</span>
                  </div>
                  <div v-for="emp in k.Emp" :key="emp.EmpId" class="userInfo">
                    <icon v-if="k.FilterType !== 1" icon="el-icon-delete" class="drop" @click="removeEmp(k,emp)" />
                    <div class="head">
                      <img
                        v-if="emp.UserHead == null || emp.UserHead == ''"
                        src="/image/defhead.png"
                        width="50"
                        height="50"
                      >
                      <el-avatar
                        v-else
                        shape="square"
                        :size="50"
                        :src="emp.UserHead | imageUri"
                      />
                    </div>
                    <div class="content">
                      <div class="item">
                        <i
                          v-if="emp.Sex == 1"
                          style="color: #409eff;margin-left:5px;"
                          class="el-icon-male"
                        />
                        <i
                          v-else-if="emp.Sex == 2"
                          style="color: #f56c6c;margin-left:5px;"
                          class="el-icon-female"
                        />
                        <el-link @click="showEmp(emp)">{{ emp.EmpName }}</el-link>
                      </div>
                      <div class="empNo">{{ emp.Dept }}</div>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item v-if="k.IsAllowCopy" label="抄送人">
                  <div style="margin-bottom: 5px;">
                    <el-button type="primary" size="mini" icon="el-icon-user" @click="chioseCopyEmp(k)" />
                  </div>
                  <div v-for="emp in k.CopyEmp" :key="emp.EmpId" class="userInfo">
                    <icon icon="el-icon-delete" class="drop" @click="removeCopy(k,emp)" />
                    <div class="head">
                      <img
                        v-if="emp.UserHead == null || emp.UserHead == ''"
                        src="/image/defhead.png"
                        width="50"
                        height="50"
                      >
                      <el-avatar
                        v-else
                        shape="square"
                        :size="50"
                        :src="emp.UserHead | imageUri"
                      />
                    </div>
                    <div class="content">
                      <div class="item">
                        <i
                          v-if="emp.Sex == 1"
                          style="color: #409eff;margin-left:5px;"
                          class="el-icon-male"
                        />
                        <i
                          v-else-if="emp.Sex == 2"
                          style="color: #f56c6c;margin-left:5px;"
                          class="el-icon-female"
                        />
                        <el-link @click="showEmp(emp)">{{ emp.EmpName }}</el-link>
                      </div>
                      <div class="empNo">{{ emp.Dept }}</div>
                    </div>
                  </div>
                </el-form-item>
              </template>
            </el-timeline-item>
            <el-timeline-item color="#f56c6c" :hide-timestamp="true" />
          </el-timeline>
        </el-form>
      </el-card>
      <div slot="footer" style="text-align: center">
        <el-button type="primary" @click="save">确定</el-button>
        <el-button @click="resetForm">重置</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择下一步"
      :visible.sync="confirmVisible"
      width="400px"
    >
      <el-radio-group v-model="chioseMethod">
        <el-radio-button :label="1">重新开始</el-radio-button>
        <el-radio-button :label="2">返回到退回节点</el-radio-button>
      </el-radio-group>
      <span slot="footer" style="text-align: center;">
        <el-button type="primary" @click="confirmNext">确 定</el-button>
        <el-button @click="confirmVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <empChoice
      :emp-id="empId"
      :is-multiple="isMultiple"
      :company-id="empFilter.CompanyId"
      :unit-id="empFilter.UnitId"
      :dept-id="empFilter.DeptId"
      :title-code="empFilter.TitleCode"
      :post-code="empFilter.PostCode"
      :is-entry="true"
      :is-leader="empFilter.IsLeader"
      :title="empTitle"
      :visible.sync="empVisible"
      @save="saveEmp"
    />
    <empModel
      :id="showEmpId"
      :visible="showVisible"
      @close="showVisible=false"
    />
  </div>
</template>

<script>
import * as flowAuditApi from '@/flow/api/flowAudit'
import empChoice from '@/components/emp/empChoice.vue'
import { FlowAuditType } from '@/flow/config/flowConfig'
import empModel from '@/components/emp/empModel.vue'
export default {
  components: {
    empChoice,
    empModel
  },
  props: {
    itemId: {
      type: String,
      default: null
    },
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      FlowAuditType,
      groups: [],
      empTitle: null,
      empId: null,
      showEmpId: null,
      showNext: false,
      empFilter: {},
      showVisible: false,
      source: null,
      nextSour: null,
      nextMethod: 0,
      chioseMethod: null,
      confirmVisible: false,
      rules: {
        ChioseNodeId: [
          {
            required: true,
            message: '审核步骤不能为空',
            trigger: 'blur'
          }
        ]
      },
      isMultiple: false,
      isCopyEmp: false,
      nodes: null,
      chioseNodeId: null,
      empVisible: false,
      curNode: null
    }
  },
  computed: {
    comId() {
      return this.$store.getters.curComId
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.reset()
        }
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    showEmp(emp) {
      this.showEmpId = emp.EmpId
      this.showVisible = true
    },
    handleClose() {
      this.showNext = false
      this.$emit('update:visible', false)
    },
    removeEmp(node, emp) {
      const index = node.Emp.findIndex(a => a.EmpId === emp.EmpId)
      if (index !== -1) {
        node.Emp.splice(index, 1)
        node.EmpId = node.EmpId.filter(c => c !== emp.EmpId)
      }
    },
    removeCopy(node, emp) {
      const index = node.CopyEmp.findIndex(a => a.EmpId === emp.EmpId)
      if (index !== -1) {
        node.CopyEmp.splice(index, 1)
        node.CopyEmpId = node.CopyEmpId.filter(c => c !== emp.EmpId)
      }
    },
    saveEmp(e) {
      if (this.isCopyEmp) {
        this.curNode.CopyEmp = e.user
        this.curNode.CopyEmpId = e.keys
      } else {
        this.curNode.Emp = e.user
        this.curNode.EmpId = e.keys
      }
    },
    async save() {
      const res = await this.validate()
      if (res === false) {
        return
      }
      const next = this.format()
      this.handleClose()
      const result = {}
      if (this.nextMethod === 1) {
        result.NextNode = next
      } else {
        result.Restore = next[0]
      }
      this.$emit('save', result)
    },
    format() {
      const node = []
      this.groups.forEach(a => {
        a.Node.forEach(c => {
          if (!a.ChioseNodeId.includes(c.ToNodeId)) {
            return
          }
          node.push({
            NodeId: c.ToNodeId,
            EmpId: c.EmpId,
            CopyEmpId: c.CopyEmpId,
            ItemId: c.ItemId,
            NextDeptId: c.NextDeptId
          })
        })
      })
      return node
    },
    resetForm() {
      const list = this.source.map(t => {
        const c = Object.assign({}, t)
        if (c.OutPolicy === 0) {
          c.ChioseNodeId = c.Node.map(a => a.ToNodeId)
          c.max = c.Node.length
          c.min = 0
        } else if (c.OutPolicy === 1) {
          c.ChioseNodeId = c.Node.map(a => a.ToNodeId)
          c.max = c.Node.length
          c.min = c.Node.length
        } else {
          c.ChioseNodeId = [c.Node[0].ToNodeId]
          c.max = 1
          c.min = 0
        }
        c.Node = c.Node.map(a => {
          const node = {
            ToNodeId: a.ToNodeId,
            NodeName: a.NodeName,
            AuditType: a.AuditType,
            NodeType: a.NodeType,
            NextDeptId: a.NextDeptId,
            ItemId: a.ItemId,
            FilterType: 0,
            IsAllowCopy: a.IsAllowCopy,
            Emp: [],
            EmpId: [],
            FilterShow: null
          }
          if (a.NodeType === 3) {
            return node
          }
          node.Emp = a.Actor.Emp
          node.EmpId = a.Actor.EmpId
          node.FilterType = a.Actor.FilterType
          node.FilterShow = a.Actor.Show
          if (a.IsAllowCopy) {
            node.CopyEmpId = []
            node.CopyEmp = []
          }
          if (a.Actor.FilterType === 2) {
            node.QueryFilter = {
              CompanyId: a.Actor.CompanyId,
              UnitId: a.Actor.UnitId,
              DeptId: a.Actor.DeptId,
              TitleCode: a.Actor.TitleCode,
              PostCode: a.Actor.PostCode,
              IsLeader: a.Actor.IsLeader
            }
          }
          return node
        })
        return c
      })
      this.groups = list
      this.showNext = true
    },
    async validate() {
      const that = this
      for (let i = 0; i < this.groups.length; i++) {
        const c = this.groups[i]
        const key = 'form_' + c.NodeId
        const res = await that.$refs[key][0].validate()
        if (res === false) {
          return false
        }
      }
      return true
    },
    chioseCopyEmp(node) {
      this.isCopyEmp = true
      this.curNode = node
      this.empFilter = {}
      this.empTitle = '选择' + node.NodeName + '抄送人'
      this.empId = node.CopyEmpId
      this.isMultiple = true
      this.empVisible = true
    },
    chioseEmp(node) {
      this.isCopyEmp = false
      this.curNode = node
      this.empFilter = node.QueryFilter
      this.empTitle = '选择' + node.NodeName + '审批人'
      this.empId = node.EmpId
      this.isMultiple = node.AuditType === 2
      this.empVisible = true
    },
    async reset() {
      const res = await flowAuditApi.GetNextStep(this.itemId)
      if (res.NextMethod === 0) {
        this.$emit('save', null)
      } else if (res.NextMethod === 1) {
        this.nextMethod = 1
        this.source = res.Nexts
      } else if (res.NextMethod === 2) {
        this.nextMethod = 2
        this.source = [res.Restore]
      } else if (res.NextMethod === 3) {
        this.nextSour = res
        this.chioseMethod = null
        this.confirmVisible = true
        return
      }
      this.resetForm()
    },
    confirmNext() {
      if (this.chioseMethod == null) {
        this.$message({
          message: '请选择下一步!',
          type: 'warning'
        })
        return
      }
      this.confirmVisible = false
      this.nextMethod = this.chioseMethod
      if (this.nextMethod === 1) {
        this.source = this.nextSour.Nexts
      } else {
        this.source = [this.nextSour.Restore]
      }
      this.resetForm()
    },
    filterNode(item) {
      if (item.ChioseNodeId == null || item.ChioseNodeId.length === 0) {
        return []
      }
      return item.Node.filter(c => item.ChioseNodeId.includes(c.ToNodeId))
    }
  }
}
</script>

<style  scoped>
.jumpNode{
    margin-right: 5px;
}
.userInfo {
  max-width: 250px;
  float: left;
  min-width: 210px;
  margin-right: 10px;
  margin-bottom: 5px;
  padding: 5px;
  height: 70px;
  border: 1px solid #90939994;
}
.userInfo .drop {
    position: relative;
    right: 2px;
    color: red;
    cursor: pointer;
    top: -10px;
}
.userInfo .head {
  width: 50px;
  float: left;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.userInfo .el-avatar {
  vertical-align: middle;
}
.userInfo .content {
  width: 160px;
  float: left;
  text-align: left;
  height: 60px;
}
.userInfo .content .item {
  text-indent: 2px;
  margin: 0;
  font-size: 16px;
  text-overflow: ellipsis;
  width: 100%;
  overflow: hidden;
  display: inline-block;
  white-space: nowrap;
  float: left;
  height: 30px;
}

.userInfo .content .empNo {
  padding-left: 10px;
  margin: 0;
  color: #82848a;
  font-size: 12px;
  text-overflow: ellipsis;
  width: 100%;
  overflow: hidden;
  display: inline-block;
  white-space: nowrap;
  float: left;
  height: 30px;
}
.userInfo .content i {
  font-weight: 600;
}
</style>
